import type { LoginParams } from './types/loginParams'
import type { LawyerQuickReply, PrivateMessageVO, UploadImageVO } from './types/message'
import type { OrderDetail } from './types/order'
import type { TextCheckResult } from './types/textCheckResult'
import type { AuditStatus, IDCardResponse, LawyerAuthInfo, UserVO, UserWrapper } from './types/userWrapper'
import type { PageParams, PageResult } from '@/http/types'
import { http, httpIm } from '@/http/alova'

export function submitLawyerAuth(lawyerAuthInfo?: LawyerAuthInfo) {
  return http.Post<boolean>('/api/v1/authentication/save_inform', {
    ...lawyerAuthInfo,
  })
}
export function submitLawyerAuthCache(lawyerAuthInfo?: LawyerAuthInfo) {
  return http.Post<boolean>('/api/v1/authentication/save_cache', {
    ...lawyerAuthInfo,
  })
}
export function lawyerAuthIsPass() {
  return http.Post<AuditStatus>('/api/v1/mine/is_pass')
}
export function findUserInfo(id: number) {
  return httpIm.Get<UserVO>(`/api/user/find/${id}`)
}
export function fetchMyInfo() {
  return httpIm.Get<UserVO>('/api/user/self')
}
export function findUserOrigin() {
  return http.Post<UserWrapper>('/api/v1/user/findUser')
}
export function sendCode(phoneNumber: string) {
  return http.Post<string>('/api/v1/core/sendPhoneCode', {
    phoneNumber,
  }, { meta: { ignoreAuth: true } })
}
export function login(loginParams: LoginParams) {
  return http.Post<UserWrapper>('/api/v1/user/codeLogin', {
    ...loginParams,
  }, { meta: { ignoreAuth: true } })
}
export function logoff() {
  return http.Post<string>('/api/v1/mine/user-logout', { meta: { ignoreAuth: true } })
}
export function bindPhone(phone: string, authCode: string) {
  return http.Post<boolean>('/api/v1/user/bindPhone', {
    phone,
    authCode,
  })
}
export function unbindPhone() {
  return http.Post<boolean>('/api/v1/user/unBindPhone')
}
export function uploadImageOriginal(filePath: string, type?: number) {
  const formData = new FormData()

  // 文件字段
  formData.append('file', {
    uri: filePath,
    type: 'image/jpeg', // 可根据实际情况修改
    name: filePath.split('/').pop() || 'file.jpg',
  } as any)

  // 可选参数
  if (type !== undefined) {
    // 如果需要加密可以改成 SecurityUtils.encrypt(String(type))
    formData.append('type', String(type))
  }
  return http.Post<string>('/api/v1/cos/userFile', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}
/** 上传普通文件，返回文件 URL */
export function fileUpload(file: File | string) {
  const formData = new FormData()
  formData.append(
    'file',
    typeof file === 'string'
      ? { uri: file, type: 'application/octet-stream', name: file.split('/').pop() } as any
      : file,
  )

  return httpIm.Post<string>('/api/file/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

/** 上传图片，返回原图和缩略图 URL */
export function imageUpload(file: File | string, isPermanent = true) {
  const formData = new FormData()
  formData.append(
    'file',
    typeof file === 'string'
      ? { uri: file, type: 'image/jpeg', name: file.split('/').pop() } as any
      : file,
  )

  return httpIm.Post<UploadImageVO>('/api/image/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    params: {
      isPermanent: String(isPermanent),
    },
  })
}
export function updateUserInfo(userVO: UserVO) {
  return httpIm.Put<number>('/api/user/update', userVO)
}
export function autoResMessages(lawyerId: number) {
  return http.Post<LawyerQuickReply[]>('/api/v1/home/auto-inform', { lawyerId })
}
export function autoReply(lawyerId: number, content: string) {
  return http.Post<PrivateMessageVO>('/api/v1/inform/auto_send', { lawyerId, content })
}
export function fetchUserOrderList(pageParams: PageParams, status?: number) {
  return http.Post<PageResult<OrderDetail>>('/api/v1/mine/orders_page', {
    status,
    page: pageParams.page,
    size: pageParams.pageSize,
  }, {
    transform(raw) {
      // raw 是 unknown，需要先断言
      const res = raw as {
        records?: OrderDetail[]
        total?: number
        pages?: number
        size?: number
        [key: string]: any
      }

      return {
        list: res.records ?? [],
        total: res.total ?? 0,
        page: res.pages ?? pageParams.page,
        pageSize: res.size ?? pageParams.pageSize,
      } satisfies PageResult<OrderDetail>
    },
  })
}
export function fetchUserOrderDetail(orderNo: string) {
  return http.Post<OrderDetail>('/api/v1/mine/order-detail', { orderNo })
}
export function userOpinion(content: string) {
  return http.Post<boolean>('/api/v1/mine/opinion', { content })
}

export function textCheck(writeContent: string) {
  return http.Post<TextCheckResult>('/api/v1/inform/textCheck', { writeContent })
}
export function reportUserVersion() {
  const version = getAppVersion()

  return http.Post<boolean>('/api/v1/user/report_user_version', { ...version })
}
/**
 * 获取当前版本信息
 */
interface AppVersionInfo {
  appName: string
  packageName: string
  version: string
  buildNumber: string
}

export function getAppVersion(): AppVersionInfo {
  const systemInfo = uni.getSystemInfoSync()

  let appName = '问必答法律咨询'
  let packageName = 'com.kyma.legal'
  let version = 'unknown'
  let buildNumber = 'unknown'

  // 小程序端
  if (systemInfo.platform.startsWith('mp-')) {
    const accountInfo = uni.getAccountInfoSync?.()
    const miniProgram = accountInfo?.miniProgram || { appId: '', envVersion: 'release', version: '' }
    appName = miniProgram.appId || appName
    packageName = miniProgram.appId || packageName
    version = miniProgram.version || version
    buildNumber = miniProgram.envVersion || buildNumber
  }
  // H5
  else if (systemInfo.platform === 'h5') {
    version = (window as any)?.APP_VERSION || version
    buildNumber = (window as any)?.APP_BUILD || buildNumber
  }
  // App iOS/Android
  else {
    appName = systemInfo.appName || appName
    packageName = systemInfo.appId || packageName

    version = systemInfo.appVersion || version
    buildNumber = systemInfo.appVersionCode || buildNumber
  }

  return { appName, packageName, version, buildNumber }
}
/**
 * 上传身份证图片并识别
 * @param filePath 本地图片路径
 * @param isFront 是否正面
 */
export function uploadIdCard(filePath: string, isFront = true) {
  const formData = new FormData()

  formData.append('file', {
    uri: filePath,
    type: 'image/jpeg',
    name: filePath.split('/').pop() || 'file.jpg',
  } as any)

  formData.append('cardSide', isFront ? 'FRONT' : 'BACK')

  return http.Post<IDCardResponse>('/api/v1/mine/IdCardOCR', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}
